package com.iseastar.guojiang.identity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.iseastar.BaseActivity2;
import com.iseastar.guojiang.app.CourierCameraActivity;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.NewParcelBean;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.tools.TextWatcherExt;
import com.shouhuobao.station.R;

import droid.frame.ui.utils.Utils;
import droid.frame.utils.http.BitmapUtils;
import droid.frame.utils.lang.Str;

/**
 * 寄件人进行实名认证
 */
public class SenderAuthenticationActivity extends BaseActivity2 implements View.OnClickListener {
    private static final int FRONT = 1;//正面身份证
    private static final int INHAND = 2;//手持身份证

    private String[] originImagePath = new String[2];//存放原始身份证图片的地址
    private String[] resultImagePath = new String[2];//存放服务器返回图片的地址
    private int type;
    private NewParcelBean parcelBean = null;

    private EditText mUserNameET;
    private EditText mIdentityNumberET;
    private ImageView mIdCardIV;
    private ImageView mIdCardInHandIV;
    private Button mSubmit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        parcelBean = (NewParcelBean) getIntent().getSerializableExtra("item");
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.courier_identity_authentication);
        super.findViewById();
        getAppTitle().setCommonTitle("录入身份信息");
        mUserNameET = (EditText) findViewById(R.id.usernameET);
        mIdentityNumberET = (EditText) findViewById(R.id.identitynumberET);
        mUserNameET.addTextChangedListener(watcherExt);
        mIdentityNumberET.addTextChangedListener(watcherExt);
        mIdCardIV = findViewById(R.id.idcard_iv);
        mIdCardIV.setOnClickListener(this);
        mIdCardInHandIV = findViewById(R.id.idcard_hand_iv);
        mIdCardInHandIV.setOnClickListener(this);
        mSubmit = findViewById(R.id.submit_bt);
        mSubmit.setOnClickListener(this);
    }

    private TextWatcherExt watcherExt = new TextWatcherExt() {
        @Override
        public void afterTextChanged(Editable s) {
            if (mUserNameET.getText().toString().trim().length() > 0 && mIdentityNumberET.getText().toString().trim().length() > 0) {
                setCourierButtonEnableStyle(mSubmit, true);
            } else {
                setCourierButtonEnableStyle(mSubmit, false);
            }
        }
    };

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(getContext(), CourierCameraActivity.class);
        switch (v.getId()) {
            //拍照身份证正面照片
            case R.id.idcard_iv:
                type = FRONT;
                startActivityForResult(intent, 1701);
                break;
            //拍照手持身份证照片
            case R.id.idcard_hand_iv:
                type = INHAND;
                startActivityForResult(intent, 1702);
                break;
            //提交实名认证
            case R.id.submit_bt:
                if (isEmpty(mUserNameET.getText().toString())) {
                    showToast("请输入真实姓名");
                    return;
                }
                if (isEmpty(mIdentityNumberET.getText().toString()) || !Str.isIdentityNumber(mIdentityNumberET.getText().toString())) {
                    showToast("请输入有效的身份证号");
                    return;
                }
                if (isEmpty(originImagePath[0]) && isEmpty(originImagePath[1])) {
                    if (parcelBean != null) {
                        showLoadingDialog("正在上传");
                        AppHttp.getInstance().courierParcelListUserIdCardSubmit(parcelBean.getOrderUserPhone(), mUserNameET.getText().toString(), mIdentityNumberET.getText().toString(), "", "");
                    } else {
                        showToast("数据有误，请重试");
                    }
                } else {
                    showLoadingDialog("正在上传");
                    if (isNotEmpty(originImagePath[0]) && isNotEmpty(originImagePath[1])) {
                        AppHttp.getInstance().postFils(MsgID.courier_parcel_list_userIdCard_image, originImagePath);
                    } else if (isNotEmpty(originImagePath[0])) {
                        AppHttp.getInstance().postFils(MsgID.courier_parcel_list_userIdCard_image, originImagePath[0]);
                    } else {
                        AppHttp.getInstance().postFils(MsgID.courier_parcel_list_userIdCard_image, originImagePath[1]);
                    }
                }
                break;
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MsgID.courier_parcel_list_userIdCard_image:
                ReqResult<String> idCardImageResult = JSON.parser(msg.obj, String.class);
                if (idCardImageResult.getResult() == null) {
                    cancelLoadingDialog();
                    showToast("图片上传失败");
                    return false;
                }
                if (checkLoginStatus(idCardImageResult)) {
                    String path = idCardImageResult.getResult().replace("\\", "").replace("[", "").replace("]", "").replace("\"", "");
                    resultImagePath = path.split(",");
                    if (resultImagePath == null || resultImagePath.length == 0) {
                        cancelLoadingDialog();
                        showToast("图片上传失败");
                        return true;
                    }
                    if (resultImagePath.length == 1) {
                        if (isNotEmpty(originImagePath[0])) {
                            AppHttp.getInstance().courierParcelListUserIdCardSubmit(parcelBean.getOrderUserPhone(), mUserNameET.getText().toString(), mIdentityNumberET.getText().toString(), resultImagePath[0], "");
                        } else {
                            AppHttp.getInstance().courierParcelListUserIdCardSubmit(parcelBean.getOrderUserPhone(), mUserNameET.getText().toString(), mIdentityNumberET.getText().toString(), "", resultImagePath[0]);
                        }
                    } else {
                        AppHttp.getInstance().courierParcelListUserIdCardSubmit(parcelBean.getOrderUserPhone(), mUserNameET.getText().toString(), mIdentityNumberET.getText().toString(), resultImagePath[0], resultImagePath[1]);
                    }
                } else {
                    cancelLoadingDialog();
                    showToast(idCardImageResult.getMessage());
                }
                return true;
            //上传身份证信息返回
            case MsgID.courier_parcel_list_userIdCard_submit:
                cancelLoadingDialog();
                ReqResult<?> idCardResult = JSON.parser(msg.obj);
                if (checkLoginStatus(idCardResult)) {
                    showToast("提交成功");
                    setResult(Activity.RESULT_OK);
                    finish();
                } else {
                    showToast(idCardResult.getMessage());
                }
                return false;
            default:
                return super.handleMessage(msg);
        }
    }

    private void handlerLoadImage(String picPath) {
        int width = getResources().getDisplayMetrics().widthPixels;
        int bitmapWidth = 0;
        if (width != 0) {
            bitmapWidth = (width - Utils.dpToPx(42, getResources())) / 2;
        } else {
            bitmapWidth = Utils.dpToPx(155, getResources());
        }
        Bitmap imageThumbnail = BitmapUtils.getImageThumbnail(picPath, bitmapWidth, Utils.dpToPx(99.5f, getResources()));
        if (imageThumbnail != null) {
            if (type == FRONT) {
                originImagePath[0] = picPath;
                mIdCardIV.setImageBitmap(imageThumbnail);
            } else {
                originImagePath[1] = picPath;
                mIdCardInHandIV.setImageBitmap(imageThumbnail);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && (1701 == requestCode || 1702 == requestCode)) {//选取要识别的图片
            String capturePath = data.getStringExtra("file");
            if (!Str.isEmpty(capturePath)) {
                handlerLoadImage(capturePath);
            }
        }
    }
}
